import time
import uuid
from django.db import transaction, connection
from django.forms import model_to_dict

from goodsApp.goodsModel.models import Goods

# 库存检验
from orderApp.cartModel.models import CartTable
from orderApp.orderDetailModel.models import OrderDetail

from orderApp.orderModel.models import Order
from orderApp.service.addressService import AddressService


class OrderService:
    def __init__(self):
        self.addressService = AddressService()
    def decreaseStorage(self,goodsId, amount):
        try:
            result = Goods.objects.get(id=goodsId)
            if result.storage >= amount:
                cursor = connection.cursor()
                # 避免出现超卖，双重检查
                cursor.execute('UPDATE goods SET storage = storage - %s WHERE id = %s AND storage >= %s'
                               , [amount, result.id,amount])
                return result
            else:
                return None
        except Exception as err:
            print("扣减库存错误: ", err)
        return False

    # 传入 cart 实体类数组 ， 保证事务执行
    @transaction.atomic
    def createOrder(self, userId):
        cartArray = CartTable.objects.filter(user_id=userId)
        goodsDict = {}
        for item in cartArray:
            goods = self.decreaseStorage(item.goods_id, item.amount)
            if goods == None:
                raise Exception("库存不足")
            goodsDict[item.goods_id] = goods
        # 扣减操作完成，生成订单
        orderId = str(uuid.uuid4()).replace('-', '')[1:10]
        total_price = 0
        # 遍历添加订单商品条目
        for item in cartArray:
            pay_price = (float)(goodsDict[item.goods_id].price) * (float)(item.amount)
            total_price += pay_price
            orderDetails = OrderDetail(order_id=orderId,
                                       goods_id=item.goods_id,
                                       amount=item.amount,
                                       pay_price=pay_price)
            orderDetails.save()
        # 保存订单
        order = Order(order_id=orderId,
                      order_status=0,
                      user_id=userId,
                      create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                      total_price=total_price)
        order.save()
        return order

    # 下单成功以后，删除购物车中的内容
    @transaction.atomic
    def deleteCart(self, userId):
        cartArray = CartTable.objects.filter(user_id=userId)
        for item in cartArray:
            c = CartTable.objects.get(id=item.id)
            c.delete()

    # 获得订单详情
    def getOrderDetailById(self, orderId):
        order = model_to_dict(Order.objects.get(order_id=orderId))
        details = OrderDetail.objects.filter(order_id=orderId)
        order["detail"] = []
        i = 0
        for dt in details:
            order["detail"].append(model_to_dict(dt, exclude="pay_price"))
            order["detail"][i]["pay_price"] = (str)(dt.pay_price)
            goods = Goods.objects.get(id=(str)(dt.goods_id))
            order["detail"][i]['img'] = goods.img
            order["detail"][i]['price'] = goods.price
            order["detail"][i]['title'] = goods.title
            i += 1
        order['address'] = model_to_dict(self.addressService.getByOrderId(orderId=orderId))
        return order

    def changeOrderStatus(self, orderId, userId, status):
        if self.checkIsVaildOrder(orderId, userId) == False:
            return False
        Order.objects.filter(orderId).update(
            status=status
        )
        return True

    # 简单的安全检查
    def checkIsVaildOrder(self, orderId, userId):
        order = Order.objects.get(orderId)
        return False if order == None else order.user_id == userId
